package com.quectel.core.module.scheduling.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.dept.dto.DeptPersonDto;
import com.quectel.core.module.dept.service.DeptPersonService;
import com.quectel.core.module.scheduling.dao.SchedulingLeaveConfigDao;
import com.quectel.core.module.scheduling.dto.SchedulingLeaveConfigDto;
import com.quectel.core.module.scheduling.dto.SchedulingLeavePersonBindingDto;
import com.quectel.core.module.scheduling.entity.SchedulingLeaveConfigEntity;
import com.quectel.core.module.scheduling.service.SchedulingLeaveConfigService;
import com.quectel.core.module.scheduling.service.SchedulingLeavePersonBindingService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@DubboService
public class SchedulingLeaveConfigServiceImpl implements SchedulingLeaveConfigService {


    public static void main(String[] args) {
        SchedulingLeaveConfigDto schedulingLeaveConfigDto = new SchedulingLeaveConfigDto();
        System.out.println(JacksonUtils.toJsonString(schedulingLeaveConfigDto));

    }

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingLeaveConfigServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SCHEDULING_LEAVE_CONFIG_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SCHEDULING_LEAVE_CONFIG_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<SchedulingLeaveConfigDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(SCHEDULING_LEAVE_CONFIG_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private SchedulingLeaveConfigDao schedulingLeaveConfigDao;
    @Autowired
    private SchedulingLeavePersonBindingService schedulingLeavePersonBindingService;
    @Autowired
    private DeptPersonService deptPersonService;
    @Autowired
    private VillageService villageService;

    @Override
    public List<SchedulingLeaveConfigDto> selectByVillageAndType(Long villageId, Byte type) {
        List<SchedulingLeaveConfigEntity> list = schedulingLeaveConfigDao.selectList(new LambdaQueryWrapper<SchedulingLeaveConfigEntity>()
                .eq(SchedulingLeaveConfigEntity::getVillageId, villageId)
                .eq(SchedulingLeaveConfigEntity::getType, type)
        );
        List<SchedulingLeaveConfigDto> result = CopyUtils.copyList(list, SchedulingLeaveConfigDto.class);
        result.forEach(this::paddingField);
        return result;
    }


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveOrUpdate(SchedulingLeaveConfigDto dto) {

        dto.setGrantRuleJson(JacksonUtils.toJsonString(dto.getGrantRule()));
        dto.setUsageRuleJson(JacksonUtils.toJsonString(dto.getUsageRule()));

        if (dto.getId() == null) {
            Long id = save(dto);
            dto.setId(id);
        } else {
            updateById(dto);
        }

        // 删除绑定关系
        schedulingLeavePersonBindingService.deleteByLeaveId(dto.getId());

        // 绑定关系到中间表
        for (DeptPersonDto personDto : dto.getPersonList()) {
            SchedulingLeavePersonBindingDto bindingDto = new SchedulingLeavePersonBindingDto();
            bindingDto.setId(Snowflake.nextId());
            bindingDto.setLeaveId(dto.getId());
            bindingDto.setDeptPersonId(personDto.getId());
            schedulingLeavePersonBindingService.save(bindingDto);
        }
    }

    @Override
    public SchedulingLeaveConfigDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SCHEDULING_LEAVE_CONFIG_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SchedulingLeaveConfigDto selectById(Long id) {
        SchedulingLeaveConfigEntity entity = schedulingLeaveConfigDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, SchedulingLeaveConfigDto.class));
    }

    @Override
    public List<SchedulingLeaveConfigDto> queryList(Map<String, Object> params) {
        List<SchedulingLeaveConfigEntity> list = schedulingLeaveConfigDao.queryList(params);
        List<SchedulingLeaveConfigDto> result = CopyUtils.copyList(list, SchedulingLeaveConfigDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<SchedulingLeaveConfigDto> queryListWithoutPadding(Map<String, Object> params) {
        List<SchedulingLeaveConfigEntity> list = schedulingLeaveConfigDao.queryList(params);
        return CopyUtils.copyList(list, SchedulingLeaveConfigDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private SchedulingLeaveConfigDto paddingField(SchedulingLeaveConfigDto dto) {
        if (dto != null) {

            if (StringUtils.isNotBlank(dto.getGrantRuleJson())) {
                dto.setGrantRule(JacksonUtils.parse(dto.getGrantRuleJson(), SchedulingLeaveConfigDto.GrantRule.class));
            }
            if (StringUtils.isNotBlank(dto.getUsageRuleJson())) {
                dto.setUsageRule(JacksonUtils.parse(dto.getUsageRuleJson(), SchedulingLeaveConfigDto.UsageRule.class));
            }
            dto.setGrantRuleJson(null);
            dto.setUsageRuleJson(null);


            if (dto.getVillageId() != null) {
                VillageDto villageDto = villageService.selectCacheById(dto.getVillageId());
                if (villageDto != null) {
                    dto.setVillageName(villageDto.getName());
                }
            }

            List<SchedulingLeavePersonBindingDto> schedulingLeavePersonBindingDtos = schedulingLeavePersonBindingService.selectByLeaveId(dto.getId());
            if (CollectionUtils.isNotEmpty(schedulingLeavePersonBindingDtos)) {
                List<DeptPersonDto> collect = schedulingLeavePersonBindingDtos.stream()
                        .map(schedulingLeavePersonBindingDto -> deptPersonService.selectCacheById(schedulingLeavePersonBindingDto.getDeptPersonId()))
                        .filter(Objects::nonNull).collect(Collectors.toList());
                dto.setPersonList(collect);
                dto.setPersonCount(collect.size());
            }


        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return schedulingLeaveConfigDao.queryTotal(params);
    }

    @Override
    public Long save(SchedulingLeaveConfigDto dto) {
        SchedulingLeaveConfigEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveConfigEntity.class);
        entity.setId(Snowflake.nextId());
        schedulingLeaveConfigDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(SchedulingLeaveConfigDto dto) {
        SchedulingLeaveConfigEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveConfigEntity.class);

        schedulingLeaveConfigDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(SchedulingLeaveConfigDto dto) {
        SchedulingLeaveConfigEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveConfigEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, schedulingLeaveConfigDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        schedulingLeaveConfigDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
